package com.my.interview.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁（不可重入的）
 * 当同一个线程两次调用,会导致第二次调用lock位置进行自旋，产生了死锁，
 * unlock调用一次，锁就被释放了
 */
public class AtomicLock  {

    private AtomicReference<Thread> owner = new AtomicReference<>();

    public void lock(){
        Thread current = Thread.currentThread();
        //利用CAS
        while (!owner.compareAndSet(null, current)){
            System.out.println("lock=========" + current.getName());
        }

    }

    public void unlock(){

        Thread current = Thread.currentThread();
        owner.compareAndSet(current, null);
        System.out.println("unlock==================" + current.getName());
    }


    public static void main(String[] args) {

        Thread thread = Thread.currentThread();

        AtomicLock atomicLock = new AtomicLock();
        atomicLock.lock();
        atomicLock.lock();
        //atomicLock.unlock();
        atomicLock.lock();
    }
}
